package com.web.utils;

import com.web.dao.UserInfoDao;
import com.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Author: wws
 * @Date: 2021/2/18 1:26
 * describe:
 */
@Component
public class SecurityUtils {


    private static UserInfoDao userInfoDao;

    @Autowired
    public void setUserInfoDao(UserInfoDao userInfoDao) {
        SecurityUtils.userInfoDao = userInfoDao;
    }


    public static BCryptPasswordEncoder passwordEncoder =new BCryptPasswordEncoder();

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new BusinessException("获取用户账户异常");
        }
    }

    /**
     * 获取用户账户
     **/
    public static Integer getUserId() {
        try {
            String username = getUsername();
            return userInfoDao.selectUserIdByUsername(username);
        } catch (Exception e) {
            throw new BusinessException("获取用户账户异常");
        }
    }

    /**
     * 获取用户
     **/
    public static User getLoginUser() {
        try {
            return (User) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new BusinessException("获取用户信息异常");
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * BCryptPasswordEncoder解密
     * @param rawPassword 原始
     * @param encodedPassword 加密密码
     * @return 结果
     */
    public static boolean checkPassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
}
